package com.neo.rabbit;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    @Bean
    public Queue helloQueue() {
        Map<String, Object> args = new HashMap<>(3);
//        声明死信交换器
        args.put("x-dead-letter-exchange", hello_dead_exchange);
//        声明死信路由键
        args.put("x-dead-letter-routing-key", hello_routing_key);
//        声明队列消息过期时间 30分钟
        args.put("x-message-ttl", 1800000);
        return QueueBuilder.durable(hello_queue).withArguments(args)
                    .build();
    }

    @Bean
    public Queue helloDeadQueue() {
        return QueueBuilder.durable(hello_dead_queue)
            .build();
    }

    public static final String hello_queue = "hello";

    public static final String hello_dead_queue = "hello_dead";

    public static final String hello_exchange = "hello_exchange";

    public static final String hello_dead_exchange = "hello_dead_exchange";

    public final static String hello_routing_key = "hello_routing_key";

    public final static String hello_dead_routing_key = "hello_dead_routing_key";

    @Autowired RabbitTemplate rabbitTemplate;

    @Bean
    public MessageRecoverer messageRecoverer(){
        return new RepublishMessageRecoverer(rabbitTemplate,RabbitConfig.hello_dead_exchange,RabbitConfig.hello_dead_routing_key);
    }


    @Bean
    public Exchange helloDeadExchange() {
        return ExchangeBuilder
            .directExchange(hello_dead_exchange)
            .durable(true)
            .build();
    }


    @Bean
    public Exchange helloExchange() {
        return ExchangeBuilder
            .directExchange(hello_exchange)
            .durable(true)
            .build();
    }

    @Bean
    public Binding helloBiding() {
        return BindingBuilder.bind(helloQueue())
            .to(helloExchange())
            .with(hello_routing_key).noargs();
    }

    @Bean
    public Binding helloDeadBiding() {
        return BindingBuilder.bind(helloDeadQueue())
            .to(helloDeadExchange())
            .with(hello_dead_routing_key).noargs();
    }



    @Bean
    public Queue neoQueue() {
        return new Queue("neo");
    }

    @Bean
    public Queue objectQueue() {
        return new Queue("object");
    }

}
